package org.basis.netty.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * closeFuture测试
 *
 * @author Mr_wenpan@163.com 2021/09/17 14:31
 */
@Slf4j
public class CloseFutureClient {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));
        log.info("{}", channelFuture.getClass());

        // 同步等待连接建立完毕，返回channel
        Channel channel = channelFuture.sync().channel();
        log.info("channel = {}", channel);

        // 新开一个线程去接收控制台输入，然后将输入信息发送给server
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.nextLine();
                // 当输入q时退出线程并关闭客户端channel
                if ("q".equals(line)) {
                    // 关闭channel，这里虽然channel关闭了但是NioEventLoopGroup并没有关闭
                    channel.close();
                    break;
                }
                channel.writeAndFlush(line);
            }
        }, "input").start();

        // 获取 CloseFuture 对象， 1) 同步处理关闭， 2) 异步处理关闭
        ChannelFuture closeFuture = channel.closeFuture();

        // 同步处理关闭
//        log.info("waiting close......");
//        closeFuture.sync();
//        log.info("同步处理关闭，处理channel关闭后的操作");
//        group.shutdownGracefully();

        // 异步处理关闭
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.info("异步处理关闭，处理channel关闭后的操作");
                // 优雅的关闭NioEventLoopGroup
                group.shutdownGracefully();
            }
        });

    }
}
